package com.chezhe.letter.jasypt;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

public class JasyptUtil {
    /**
     * 秘钥
     */
    private static String SECRET = "chezhe";

    private static PooledPBEStringEncryptor holder = null;

    public static PooledPBEStringEncryptor buildEncryptorConfig() {
        if (holder == null) {
            PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
            SimpleStringPBEConfig config = new SimpleStringPBEConfig();
            config.setPassword(SECRET);
            config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
            config.setKeyObtentionIterations("1000");
            config.setPoolSize("1");
            config.setProviderName("SunJCE");
            config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
            config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
            config.setStringOutputType("base64");
            encryptor.setConfig(config);
            holder = encryptor;
        }
        return holder;
    }

    public static String encrypt(String value) {
        PooledPBEStringEncryptor encryptor = buildEncryptorConfig();
        String encryptString = encryptor.encrypt(value);
        return "ENC(" + encryptString + ")";
    }

    public static String decrypt(String value) {
        PooledPBEStringEncryptor encryptor = buildEncryptorConfig();
        value = value.substring(4, value.length() - 1);
        String decryptString = encryptor.decrypt(value);
        return decryptString;
    }

    public static void main(String[] args) {
        String password = "chezhe";
        System.out.println(encrypt(password));
        System.out.println(decrypt(encrypt(password)));
    }
}